/**
 * 
 */
package it.polimi.leo.a3;

import it.polimi.leo.mw.IMiddleWare;
import it.polimi.leo.mw.IMiddleWareGroup;
import it.polimi.leo.mw.IMiddleWareNode;
import it.polimi.leo.mw.IMiddlewareMessage;
import it.polimi.leo.mw.JoinGroupException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Lev
 *
 */
public class ElectionManager implements Runnable {

    private boolean decide = true;
    private boolean decTake = false;
    private long electionTime;
    private IMiddleWare mw;
    private IMiddleWareNode mwNode;
    //private IMiddleWareGroup group;		//start election in  this group

    /**
     * @param electionTime
     * @param msgfactory
     * @param group
     * @throws JoinGroupException
     */
    public ElectionManager(long electionTime,
            IMiddleWare mw, IMiddleWareGroup group) throws JoinGroupException {
        this.mw = mw;
        this.electionTime = electionTime;
        this.mwNode = mw.createNode(group);
    }
    
    @Override
    public void run() {
        IMiddlewareMessage msg = mw.getIMiddlewareMessageFactory().createGiveFitnessMsg(mwNode.getJoinedGroup());
        mwNode.sendMsg(msg);

        IMiddleWareNode newSuperviser = mwNode.getGroupListners().get(0);
        //TODO: Wait for fitness response, elect
        
        msg = mw.getIMiddlewareMessageFactory().createBecomeAsuperviserMsg(this.mwNode.getJoinedGroup());
        mwNode.sendMsgTo(msg, newSuperviser);
        try {
            mwNode.leaveGroup();
        } catch (JoinGroupException ex) {
            Logger.getLogger(ElectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
